package com.znsd.zl.app.user.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.znsd.zl.app.user.annotation.Login;
import com.znsd.zl.app.user.entity.AppUserEntity;
import com.znsd.zl.app.user.service.IAppUserService;
import com.znsd.zl.app.user.utils.RedisUtils;
import com.znsd.zl.app.user.utils.StringUtils;
import com.znsd.zl.app.user.vo.req.AppUserLoginReqVO;
import com.znsd.zl.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 *  客户端用户登录
 * </p>
 *
 * @ClassName AppUserLogin
 * @Description TODO
 * @Author jaypdd
 * @Date 2020/8/25 15:27
 * @Version v1.0
 */
@Slf4j
@RestController
@RequestMapping("/user")
public class AppUserLogin {

	@Resource
	private IAppUserService service;

	@Resource
	private RedisUtils redisUtils;

	/**
	 * 获取当前登录的用户信息
	 * @param request   http请求对象
	 */
	@GetMapping("/info")
	public R getInfo(HttpServletRequest request) {
		// 获取请求头中携带的token
		String token = request.getHeader("token");
		AppUserEntity userInfo = service.getUserInfo(token);
		if ( userInfo == null ) {
			return R.error("获取失败");
		}
		return R.ok().put("data", StringUtils.phoneEncrypt(userInfo));
	}

	/**
	 * wx小程序用户登录
	 * @param reqVO     小程序的临时登录凭证code
	 * @return          返回access_token
	 */
	@PostMapping("/login")
	public R login(@RequestBody AppUserLoginReqVO reqVO) {
		String token = service.login(reqVO.getCode());
		if ( token != null ) {
			return R.ok().put("access_token", token);
		}
		return R.error("授权失败");
	}

	/**
	 * 用户退出登录
	 * @param request   退出登录
	 * @return
	 */
	@GetMapping("/logout")
	@Login
	public R logout(HttpServletRequest request) {
		String token = request.getHeader("token");
		service.logout(token);
		return R.ok();
	}

	/**
	 * 根据code换取openid判断用户是否新用户
	 * @param code  换取openid凭证
	 * @return      存在返回 status true 不存在返回 false
	 */
	@GetMapping("/verifyUserExists")
	public R verifyUserExists(@RequestParam String code) {
		boolean status = service.verifyUserExists(code);
		return R.ok().put("status", status);
	}


}
